package com.itheima.tlias.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.tlias.mapper.StudentMapper;
import com.itheima.tlias.pojo.PageResult;
import com.itheima.tlias.pojo.Student;
import com.itheima.tlias.pojo.StudentDateOption;
import com.itheima.tlias.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class StudentServiceImpl implements StudentService {
	@Autowired
	private StudentMapper studentMapper;

	@Override
	public Student getById(Integer id) {
		return studentMapper.getById(id);
	}

	@Override
	public PageResult<Student> page(Integer clazzId, Integer degree, String name, Integer page, Integer pageSize) {
		PageHelper.startPage(page, pageSize);

		Page<Student> studentPage = (Page<Student>) studentMapper.page(clazzId, degree, name);

		return new PageResult<>(studentPage.getTotal(), studentPage);
	}

	@Override
	public void save(Student student) {
		student.setCreateTime(LocalDateTime.now());
		student.setUpdateTime(LocalDateTime.now());
		student.setViolationCount(0);
		student.setViolationScore(0);
		studentMapper.save(student);
	}

	//@Override
	//public void deleteById(Integer id) {
	//	Student oldStudent = studentMapper.getById(id);
	//	if (oldStudent == null) throw new RuntimeException("要删除的学员不存在");
	//	studentMapper.deleteById(id);
	//}

	@Override
	public void deleteByIds(List<Integer> idList) {
		studentMapper.deleteByIds(idList);
	}

	@Override
	public void updateScore(Integer id, Integer score) {
		studentMapper.updateScore(id, score);
	}

	@Override
	public void update(Student student) {
		if (student == null || student.getId() == null) {
			throw new RuntimeException("学生对象或ID不能为空，更新失败");
		}
		if (studentMapper.getById(student.getId()) == null) {
			throw new RuntimeException("没有id为" + student.getId() + "的学员，更新失败");
		}
		student.setUpdateTime(LocalDateTime.now());
		studentMapper.update(student);
	}

	@Override
	public List<Map<String, Object>> getDegreeData() {

		return studentMapper.getDegreeData();
	}

	@Override
	public StudentDateOption getStudentCountData() {
		List<Map<String, Object>> list = studentMapper.getStudentCountData();
		List<Object> clazzList = list.stream().map(map -> map.get("clazzList")).toList();
		List<Object> dataList = list.stream().map(map -> map.get("dataList")).toList();
		return new StudentDateOption(clazzList, dataList);
	}
}
